﻿using Autofac;
using Infrastructure.Data;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Data;
using System.IO;
using System.Reflection;
using System;
using Infrastructure.IService;
using Infrastructure.Services;

namespace GitSyncApp
{
    public static class ConfigureInfraServices
    {
        public static App AddInfraService(this App app, ContainerBuilder builder)
        {
            var configuration = CreateConfigurationRoot();

            // Configuration
            builder.RegisterInstance(configuration).As<IConfiguration>().SingleInstance();

            // DbContext
            builder
                .Register(c =>
                {
                    var options = new DbContextOptionsBuilder<DataContext>();
                    options.UseSqlite(configuration.GetConnectionString("SQLite"), sqliteOptions =>
                    {
                        sqliteOptions.MigrationsAssembly(Assembly.GetExecutingAssembly()?.GetName()?.FullName);
                        sqliteOptions.CommandTimeout(configuration.GetValue("ConnectionTimeout", 30));
                    });
                    return options;
                })
                .InstancePerDependency();
            builder.RegisterType<DataContext>().AsSelf().InstancePerLifetimeScope();

            // Dapper
            builder
                .Register(c =>
                {
                    return new SqliteConnection(configuration.GetConnectionString("SQLite"));
                })
                .As<IDbConnection>()
                .InstancePerLifetimeScope();

            // Infrastructure Service
            builder.RegisterAssemblyTypes(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "Infrastructure.Services.dll")))
                .AsImplementedInterfaces()
                .InstancePerDependency();

            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();

            return app;
        }

        public static IConfiguration CreateConfigurationRoot()
        {
            var builder = new ConfigurationBuilder();

            var path = Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName, "Config");
            var files = Directory.GetFiles(path, "*.json", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                builder.AddJsonFile(file, true, true);
            }

            return builder.Build();
        }
    }
}
